package org.easy.chatai;


import org.easy.chatai.model.AiMessage;
import org.easy.chatai.model.ChatModelRequest;
import org.easy.chatai.model.ChatModelResponse;
import org.easy.sse.SseRestTemplate;
import org.easy.sse.dto.EventSourceWriteEventCallback;

import java.util.ArrayList;
import java.util.List;

/**
 * 通用方法封装工具类
 */
public class ChatAiTemplate {

    private final ChatAiClient chatAiClient;
    private final SseRestTemplate sseRestTemplate;

    public ChatAiTemplate(ChatAiClient client, SseRestTemplate sseRestTemplate) {
        this.chatAiClient = client;
        this.sseRestTemplate = sseRestTemplate;
    }

    public ChatModelResponse chatBlocking(String url, String token, String model, List<AiMessage> histories) {
        ChatModelRequest chatModelRequest = new ChatModelRequest();
        chatModelRequest.setModel(model);
        chatModelRequest.setMessages(histories);
        chatModelRequest.setStream(false);
        return chatAiClient.chatBlocking(url, token, chatModelRequest);
    }

    public ChatModelResponse chatBlocking(String url, String token, String model, String systemSetting) {
        ArrayList<AiMessage> histories = new ArrayList<>();
        histories.add(0, AiMessage.system().content(systemSetting).build());

        ChatModelRequest chatModelRequest = new ChatModelRequest();
        chatModelRequest.setModel(model);
        chatModelRequest.setMessages(histories);
        chatModelRequest.setStream(false);
        return chatAiClient.chatBlocking(url, token, chatModelRequest);
    }

    public ChatModelResponse chatBlockingJson(String url, String token, String model, List<AiMessage> histories) {
        ChatModelRequest chatModelRequest = new ChatModelRequest();
        chatModelRequest.setModel(model);
        chatModelRequest.setMessages(histories);
        chatModelRequest.setStream(false);
        return chatAiClient.chatBlocking(url, token, chatModelRequest);
    }

    public ChatModelResponse chatBlockingJson(String url, String token, String model, String systemSetting) {
        ArrayList<AiMessage> histories = new ArrayList<>();
        histories.add(0, AiMessage.system().content(systemSetting).build());

        ChatModelRequest chatModelRequest = new ChatModelRequest();
        chatModelRequest.setModel(model);
        chatModelRequest.setMessages(histories);
        chatModelRequest.setStream(false);
        return chatAiClient.chatBlocking(url, token, chatModelRequest);
    }


    public String chatStreaming(String url, String token, String model, List<AiMessage> histories, EventSourceWriteEventCallback sseResponseCallbackClient) {
        ChatModelRequest chatModelRequest = new ChatModelRequest();
        chatModelRequest.setModel(model);
        chatModelRequest.setMessages(histories);
        chatModelRequest.setStream(true);
        return sseRestTemplate.postJsonCallback(url, token, chatModelRequest, sseResponseCallbackClient);
    }

}